#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>

int createdir(const char *path)
{
	char pathdir[256];
	char curdir[256];
	char *curr = NULL;
	char *next = NULL;

	if (path == NULL || strlen(path) == 0)
		return -1;

	memset(pathdir, 0, 256);
	strncpy(pathdir, path, strlen(path));

	memset(curdir, 0, 256);

	if (pathdir[0] == '/')
		curr = pathdir + 1;
	else
		curr = pathdir;

	while ((next = strchr(curr, '/')) != NULL)
	{
		strncpy(curdir, pathdir, next - pathdir);
		curdir[next-pathdir] = '\0';

		if (mkdir(curdir, 0766) == -1)
		{
			if (errno != EEXIST)
			{
				return -1;
			}
		}

		curr = next + 1;
	}

	if (mkdir(pathdir, 0766) == -1)
	{
		if (errno != EEXIST)
		{
			return -1;
		}
	}

	return 0;
}

